package com.bot.edu.informationmanage.users.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.date.DateTime;
import com.bot.edu.informationmanage.education.entity.Education;
import com.bot.edu.informationmanage.education.service.IEducationService;
import com.bot.edu.informationmanage.stu.entity.Stu;
import com.bot.edu.informationmanage.stu.service.IStuService;
import com.bot.edu.noticessystem.notices.entity.Notices;
import com.bot.edu.noticessystem.notices.service.INoticesService;
import com.bot.edu.utils.SnowFlake;
import com.bot.edu.utils.ToNotices;
import jdk.nashorn.internal.runtime.Undefined;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.bot.edu.informationmanage.users.entity.UserInfo;
import com.bot.edu.informationmanage.users.service.IUserInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.QueryTableDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 用户表
 * @Author: jeecg-boot
 * @Date:   2022-04-02
 * @Version: V1.0
 */
@Api(tags="用户表")
@RestController
@RequestMapping("/users/userInfo")
@Slf4j
public class UserInfoController extends JeecgController<UserInfo, IUserInfoService> {
	@Autowired
	private IUserInfoService userInfoService;

	@Autowired
	private IEducationService educationService;

	@Autowired
    private IStuService stuService;

	@Autowired
    private INoticesService noticesService;

     @Value("${webapp}")
     public String uploadPath;
	/**
	 * 分页列表查询
	 *
	 * @param userInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "用户表-分页列表查询")
	@ApiOperation(value="用户表-分页列表查询", notes="用户表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<UserInfo>> queryPageList(UserInfo userInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<UserInfo> queryWrapper = QueryGenerator.initQueryWrapper(userInfo, req.getParameterMap());
		Page<UserInfo> page = new Page<UserInfo>(pageNo, pageSize);
		IPage<UserInfo> pageList = userInfoService.page(page, queryWrapper);

		List<UserInfo> userInfos = pageList.getRecords();
		List<Education> educations = educationService.list();

		for (UserInfo userinfo : userInfos) {
			try {
				userInfo.getUserEdu();
				for (Education education : educations) {
					if (userinfo.getUserEdu().equals(education.getEduId())){
						userinfo.setUserEdu(education.getEduName());
					}
				}
			}catch (Exception e){
				continue;
			}


		}


		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param userInfo
	 * @return
	 */
	@AutoLog(value = "用户表-添加")
	@ApiOperation(value="用户表-添加", notes="用户表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody UserInfo userInfo) {

		//雪花算法生成用户编号
		userInfo.setUserId(SnowFlake.getId());
		userInfoService.save(userInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param userInfo
	 * @return
	 */
	@AutoLog(value = "用户表-编辑")
	@ApiOperation(value="用户表-编辑", notes="用户表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody UserInfo userInfo) {
		userInfoService.updateById(userInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户表-通过id删除")
	@ApiOperation(value="用户表-通过id删除", notes="用户表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		userInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "用户表-批量删除")
	@ApiOperation(value="用户表-批量删除", notes="用户表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.userInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "用户表-通过id查询")
	@ApiOperation(value="用户表-通过id查询", notes="用户表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<UserInfo> queryById(@RequestParam(name="id",required=true) String id) {
		UserInfo userInfo = userInfoService.getById(id);
		if(userInfo==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(userInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param userInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, UserInfo userInfo) {
        return super.exportXls(request, userInfo, UserInfo.class, "用户表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, UserInfo.class);
    }


     /**
      * 发送验证码
      * @param tel
      * @param session
      * @return
      */
     @GetMapping("/sendCode/{tel}/{type}")
     public Result<?> sendCode(@PathVariable String tel,@PathVariable String type, HttpSession session){
         Result<Object> result = new Result<>();
         try {
             result.setSuccess(true);
             result.setMessage("发送成功");
             userInfoService.sendCode(tel,type,session);
         }catch (Exception e){
             result.setSuccess(false);
             result.setMessage(e.getMessage());
         }
         return result;
     }

     /**
      * app注册
      * @param code
      * @param tel
      * @param password
      * @param session
      * @return
      */
     @GetMapping("/register/{tel}/{code}/{password}")
     public Result<Object> sendCode(@PathVariable Integer code, @PathVariable String tel,@PathVariable String password, HttpSession session){
         try {
             Integer valCode = (Integer) session.getAttribute("code" + tel);
             if (valCode.equals(code)){
                 UserInfo userInfo = new UserInfo();
                 userInfo.setUserId(SnowFlake.getId());
                 userInfo.setUserPhone(tel);
                 userInfo.setUserUname(tel);
                 userInfo.setUserPwd(password);
                 userInfoService.save(userInfo);
                 Notices notices = ToNotices.toNoticesById(userInfo.getUserId(), "注册成功，欢迎来到博添实训");
                 noticesService.save(notices);
                 return Result.ok(userInfo);
             }else {
                 return Result.error("验证码有误");
             }
         } catch (Exception e) {
             return Result.error("验证码不存在");
         }
     }

     /**
      * 重置密码
      * @param code
      * @param tel
      * @param password
      * @param session
      * @return
      */
     @GetMapping("/startRePass/{tel}/{code}/{password}")
     public Result<Object> startRePass(@PathVariable Integer code, @PathVariable String tel,@PathVariable String password, HttpSession session){
         try {
             Integer valCode = (Integer) session.getAttribute("code" + tel);
             if (valCode.equals(code)){
                 QueryWrapper<Stu> stuQueryWrapper = new QueryWrapper<>();
                 stuQueryWrapper.lambda().eq(Stu::getStuPhone,tel);
                 Stu stu = stuService.getOne(stuQueryWrapper);
                 QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
                 userInfoQueryWrapper.lambda().eq(UserInfo::getUserPhone,tel);
                 UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);
                 if (stu==null){
                     if (userInfo==null){
                         return Result.error("用户不存在");
                     }else {
                         userInfo.setUserPwd(password);
                         userInfoService.update(userInfo,userInfoQueryWrapper);
                         return Result.ok();
                     }
                 }else {
                     stu.setStuPassword(password);
                     stuService.update(stu,stuQueryWrapper);
                     userInfo.setUserPwd(password);
                     userInfoService.update(userInfo,userInfoQueryWrapper);
                     Notices notices = ToNotices.toNoticesById(userInfo.getUserId(), "密码重置成功");
                     noticesService.save(notices);
                     return Result.ok();
                 }
             }else {
                 return Result.error("验证码有误");
             }
         } catch (Exception e) {
             return Result.error("验证码不存在");
         }
     }

     /**
      * 学生集合
      * @return
      */
     @GetMapping("/getUserList")
     public Result<?> getUserList(){
         List<UserInfo> userInfoList = userInfoService.list();
         return Result.ok(userInfoList);
     }

     /**
      * 验证手机号是否已经注册
      * @param userPhone
      * @return
      */
     @GetMapping("/toPhone")
     public Result<?> toPhone(String userPhone){
         QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
         userInfoQueryWrapper.lambda().eq(UserInfo::getUserPhone,userPhone);
         UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);
         if (userInfo == null){
             return Result.ok();
         }else {
             return Result.error("该手机号已注册");
         }
     }


}
